<template>
  <div class="user-index">
    <div class="user-content">
      <div class="profile-card">
        <div class="card-header">
          <h2 class="card-title">個人信息</h2>
        </div>
        <div class="card-body">
          <div class="item avatar-item">
            <div class="item-content">
              <span class="label avatar-label">我的頭像</span>
              <div class="avatar-wrapper">
                <img class="user-header" :src="userInfo.avatar" alt="用戶頭像" />
                <div class="avatar-overlay">
                  <el-upload class="upload-demo" :action="upLoadUrl" :on-success="handleSuccess" :show-file-list="false"
                    :multiple="false" :limit="3" :on-exceed="handleExceed" :on-error="handleError" :headers="myHeaders"
                    :file-list="fileList">
                    <i class="el-icon-camera"></i>
                    <span>更換頭像</span>
                  </el-upload>
                </div>
              </div>
            </div>
          </div>
          <div class="item text-info">
            <div class="item-content">
              <span class="label">我的昵稱</span>
              <span class="txt">{{ userInfo.nickname }}</span>
            </div>
            <button class="edit-btn" @click="editName">
              <i class="el-icon-edit"></i>
              修改
            </button>
          </div>
          <div class="item text-info">
            <div class="item-content">
              <span class="label">手機號</span>
              <span class="txt">{{ userInfo.phone }}</span>
            </div>
            <button class="edit-btn" @click="isPhone = true">
              <i class="el-icon-edit"></i>
              修改
            </button>
          </div>
          <div class="item text-info">
            <div class="item-content">
              <span class="label">我的ID</span>
              <span class="txt user-id">{{ userInfo.uid }}</span>
            </div>
          </div>
          <div class="item text-info">
            <div class="item-content">
              <span class="label">密碼設置</span>
              <span class="txt password-mask">••••••</span>
            </div>
            <button class="edit-btn" @click="isPassword = true">
              <i class="el-icon-edit"></i>
              修改密碼
            </button>
          </div>
        </div>
      </div>
      <div class="logout-section">
        <button class="logout-btn" @click="longOut">
          <i class="el-icon-switch-button"></i>
          退出登錄
        </button>
      </div>
    </div>
    <!-- 修改密碼 -->
    <el-dialog title="修改密碼" :visible.sync="isPassword" width="545px" :before-close="handleClose">
      <div class="form-box">
        <div class="input-item">
          <el-input placeholder="請輸入手機號碼" v-model="userInfo.phone" disabled>
            <template slot="prepend">+86</template>
          </el-input>
        </div>
        <div class="input-item">
          <el-input placeholder="請輸入验证碼" v-model="passwordData.code">
          </el-input>
          <el-button plain class="code-box" @click="getVerify(0)" :disabled="disabled">{{ text }}
          </el-button>
        </div>
        <div class="input-item">
          <el-input placeholder="請輸入新密碼" type="password" v-model="passwordData.newPassword">
          </el-input>
        </div>
      </div>
      <div class="dialog-footer">
        <span slot="footer">
          <el-button type="primary" @click="bindPassword">確 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </span>
      </div>
    </el-dialog>
    <!-- 修改手機號碼 -->
    <el-dialog title="修改手機號碼" :visible.sync="isPhone" width="545px" :before-close="handleClose">
      <div class="form-box">
        <div class="input-item">
          <el-input placeholder="請輸入新手機號碼" v-model="phoneData.newPhone">
            <template slot="prepend">+86</template>
          </el-input>
        </div>
        <div class="input-item">
          <el-input placeholder="請輸入验证碼" v-model="phoneData.code">
          </el-input>
          <el-button plain class="code-box" @click="getVerify(1)" :disabled="disabled">{{ text }}
          </el-button>
        </div>
      </div>
      <div class="dialog-footer">
        <span slot="footer">
          <el-button type="primary" @click="bindNewPhone">確 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </span>
      </div>
    </el-dialog>
    <Verify v-if="verifyModal" @success="success" captchaType="blockPuzzle"
      :imgSize="{ width: '330px', height: '155px' }" ref="verify"></Verify>
  </div>
</template>

<script>
import sendVerifyCode from "@/mixins/SendVerifyCode";
import { Message, MessageBox } from "element-ui";
import Verify from "@/components/verifition/Verify";

import setting from "~/setting";

export default {
  name: "index",
  auth: "guest",
  components: { Verify },
  mixins: [sendVerifyCode],
  data() {
    return {
      userInfo: {},
      fileList: [],
      upLoadUrl: setting.apiBaseURL + "/upload/image",
      myHeaders: {},
      isPassword: false, //修改密碼号碼弹窗
      verifyModal: false,
      passwordData: {
        phone: "",
        code: "",
        newPassword: "",
      },
      isPhone: false, //修改手機號碼弹窗
      phoneData: {
        code: "",
        newPhone: "",
      },
      keyCode: "",
      modalType: 0
    };
  },
  fetch({ store }) {
    store.commit("isHeader", true);
    store.commit("isFooter", true);
  },
  head() {
    return {
      title: "賬戶管理-" + this.$store.state.titleCon,
    };
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      window.scrollTo(0, 0);
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      setTimeout(() => {
        window.scrollTo(0, 0);
      }, 50);
    });
    let local = this.$cookies.get("auth.strategy");
    this.myHeaders = {
      Authorization: this.$cookies.get(`auth._token.${local}`),
    };
    this.userInfo = this.$auth.user;
    this.getCodeKey();
  },
  methods: {
    getVerify(type) {
      this.verifyModal = true;
      this.modalType = type
      this.$nextTick(e => {
        this.$refs.verify.show();
      });
    },
    success(params) {
      this.getCode(params);
    },
    // 获取验证碼的key
    getCodeKey() {
      this.$axios.$get("/verify_code").then((res) => {
        this.keyCode = res.key;
      });
    },
    handleSuccess(data) {
      if (data.status == 400) {
        return this.$message.error(data.msg);
      }
      this.$axios
        .post("user/edit", {
          avatar: data.data.url,
          nickname: this.userInfo.nickname,
        })
        .then((res) => {
          let jsonData = JSON.parse(JSON.stringify(this.userInfo));
          jsonData.avatar = data.data.url;
          this.$auth.$storage.setUniversal("user", jsonData);
          this.userInfo = this.$auth.user;
          this.$message.success("修改成功");
        })
        .catch((error) => {
        });
    },
    handleExceed(files, fileList) {
      this.$message.warning("请勿频繁重复上传");
    },
    handleError(file, fileList) {
      this.$message.error("上传失败");
    },
    // 修改昵稱
    editName() {
      MessageBox.prompt("請輸入昵稱", "提示", {
        confirmButtonText: "確定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "昵稱不能為空",
      })
        .then(({ value }) => {
          this.$axios
            .post("user/edit", {
              nickname: value,
              avatar: this.userInfo.avatar,
            })
            .then((res) => {
              let jsonData = JSON.parse(JSON.stringify(this.userInfo));
              jsonData.nickname = value;
              this.$auth.$storage.setUniversal("user", jsonData);
              this.userInfo = this.$auth.user;
              this.$message.success("修改成功");
            });
        })
        .catch(() => {
        });
    },
    // 退出登錄
    async longOut() {
      let val = this.$cookies.get("auth.strategy");
      await this.$auth.logout(val).then((res) => {
        this.$store.commit("cartNum", 0);
        this.$router.replace({
          path: "/",
        });
      });
    },
    // 修改密碼
    bindPassword() {
      let that = this;
      if (!that.passwordData.code) return Message.error("请填写验证碼");
      if (!that.passwordData.newPassword) return Message.error("请填写新密碼");
      this.$axios
        .post("register/reset", {
          account: that.userInfo.phone,
          captcha: that.passwordData.code,
          password: that.passwordData.newPassword,
        })
        .then((res) => {
          Message.success(res.msg);
          this.isPassword = false;
          this.passwordData.phone = "";
          this.passwordData.code = "";
          this.passwordData.newPassword = "";
        })
        .catch((err) => {
          return Message.error(err);
        });
    },
    handleClose() {
      this.isPassword = false;
      this.isPhone = false;
      this.passwordData.phone = "";
      this.passwordData.code = "";
      this.passwordData.newPassword = "";
      this.phoneData.code = "";
      this.phoneData.newPhone = "";
    },
    // 發送验证碼
    async getCode(data) {
      let that = this;
      await this.$axios
        .post("/register/verify", {
          phone: that.modalType ? that.phoneData.newPhone : that.userInfo.phone,
          type: "mobile",
          key: that.keyCode,
          captchaType: "blockPuzzle",
          captchaVerification: data.captchaVerification
        })
        .then((res) => {
          Message.success(res.msg);
          that.sendCode();
        })
        .catch((res) => {
          Message.error(res);
        });
    },
    // 绑定新手機號碼
    async bindNewPhone() {
      let that = this;
      if (!that.phoneData.newPhone) return Message.error("请填写新手機號碼");
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.phoneData.newPhone))
        return Message.error("請輸入正確的手機號碼");
      if (!that.phoneData.code) return Message.error("请填写验证碼");
      this.$axios
        .post("user/updatePhone", {
          phone: that.phoneData.newPhone,
          captcha: that.phoneData.code,
          key: that.keyCode,
        })
        .then((res) => {
          Message.success(res.msg);
          this.userInfo.phone = that.phoneData.newPhone
          this.isPhone = false;
          this.phoneData.newPhone = "";
          this.phoneData.code = "";
        })
        .catch((err) => {
          return Message.error(err);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.user-index {
  min-height: 100vh;
  background: #f8f9fa;
  padding-top: 60px;

  .page-header {
    text-align: center;
    margin-bottom: 30px;

    .page-title {
      font-size: 28px;
      font-weight: 600;
      margin: 0 0 8px 0;
      color: #282828;
    }

    .page-subtitle {
      font-size: 14px;
      margin: 0;
      font-weight: 400;
      color: #666;
    }
  }

  .user-content {
    max-width: 600px;
    margin: 0 auto;

    .profile-card {
      background: white;
      border-radius: 0;
      box-shadow: 0 3px 20px rgba(0, 0, 0, 0.06);
      overflow: hidden;
      margin-bottom: 20px;

      .card-header {
        background: #f8f9fa;
        padding: 24px;
        text-align: center;
        border-bottom: 1px solid #dee2e6;

        .card-title {
          color: #282828;
          font-size: 16px;
          font-weight: 600;
          margin: 0;
        }
      }

      .card-body {
        padding: 0;

        .item {
          padding: 16px 24px;
          border-bottom: 1px solid #f0f0f0;
          display: flex;
          align-items: center;
          justify-content: space-between;
          transition: all 0.3s ease;

          &:last-child {
            border-bottom: none;
          }

          &:hover {
            background: #f8f9fa;
          }

          .item-content {
            display: flex;
            align-items: center;
            flex: 1;

            .label {
              font-weight: 500;
              color: #282828;
              min-width: 80px;
              font-size: 14px;
            }

            .avatar-label {
              text-align: center;
            }

            .txt {
              color: #666;
              font-size: 14px;
              margin-left: 16px;

              &.user-id {
                font-family: 'Courier New', monospace;
                background: #f8f9fa;
                padding: 4px 8px;
                border-radius: 6px;
                font-size: 12px;
              }

              &.password-mask {
                font-size: 16px;
                letter-spacing: 2px;
              }
            }
          }

          &.avatar-item {
            flex-direction: column;
            align-items: flex-start;
            padding: 24px;

            .item-content {
              flex-direction: column;
              align-items: center;
              width: 100%;

              .label {
                margin-bottom: 16px;
                font-size: 14px;
              }

              .avatar-wrapper {
                position: relative;
                display: inline-block;

                .user-header {
                  width: 100px;
                  height: 100px;
                  border-radius: 50%;
                  border: 2px solid #f0f0f0;
                  transition: all 0.3s ease;
                  object-fit: cover;

                  &:hover {
                    border-color: #e0e0e0;
                  }
                }

                .avatar-overlay {
                  position: absolute;
                  top: 0;
                  left: 0;
                  right: 0;
                  bottom: 0;
                  background: rgba(0, 0, 0, 0.5);
                  border-radius: 50%;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  opacity: 0;
                  transition: all 0.3s ease;
                  cursor: pointer;

                  &:hover {
                    opacity: 1;
                  }

                  .upload-demo {
                    color: white;
                    text-align: center;

                    i {
                      font-size: 18px;
                      margin-bottom: 4px;
                      display: block;
                    }

                    span {
                      font-size: 12px;
                    }
                  }
                }
              }
            }
          }

          .edit-btn {
            background: #f8f9fa;
            color: #495057;
            border: 1px solid #dee2e6;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 4px;
            font-weight: 500;

            &:hover {
              background: #e9ecef;
              border-color: #adb5bd;
              color: #212529;
              transform: translateY(-1px);
            }

            i {
              font-size: 12px;
            }
          }
        }
      }
    }

    .logout-section {
      text-align: center;

      .logout-btn {
        background: #f8f9fa;
        color: #495057;
        border: 1px solid #dee2e6;
        padding: 12px 24px;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 8px;

        &:hover {
          background: #e9ecef;
          border-color: #adb5bd;
          color: #212529;
          transform: translateY(-1px);
        }

        i {
          font-size: 16px;
        }
      }
    }
  }
}

// 對話框樣式優化
.input-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .el-input {
    flex: 1;

    ::v-deep .el-input__inner {
      border-radius: 6px;
      border: 1px solid #dee2e6;
      padding: 12px 16px;
      font-size: 14px;
      transition: all 0.3s ease;

      &:focus {
        border-color: #adb5bd;
        box-shadow: 0 0 0 2px rgba(173, 181, 189, 0.1);
      }
    }
  }

  .code-box {
    width: 100px;
    height: 40px;
    margin-left: 12px;
    border-radius: 6px;
    background: #495057;
    color: white;
    border: 1px solid #495057;
    font-weight: 500;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover {
      background: #343a40;
      border-color: #343a40;
      transform: translateY(-1px);
    }

    &:disabled {
      background: #f8f9fa;
      color: #6c757d;
      border-color: #dee2e6;
      transform: none;
    }
  }
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #dee2e6;
  gap: 12px;

  .el-button {
    width: 120px;
    height: 40px;
    border-radius: 6px;
    font-weight: 500;
    font-size: 14px;
    transition: all 0.3s ease;

    &.el-button--primary {
      background: #495057;
      border: 1px solid #495057;

      &:hover {
        background: #343a40;
        border-color: #343a40;
        transform: translateY(-1px);
      }
    }

    &:not(.el-button--primary) {
      background: #f8f9fa;
      color: #495057;
      border: 1px solid #dee2e6;

      &:hover {
        background: #e9ecef;
        border-color: #adb5bd;
        transform: translateY(-1px);
      }
    }
  }
}

.user-header {
  transition: all 0.3s ease !important;

  &:hover {
    border-color: #e0e0e0 !important;
  }
}
</style>
